package com.huangmingfu;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @Author: 黄名富
 * @Description: Cglib 动态代理
 */
public class CglibDynamicProxy {

    private static class RealRequest {

        public RealRequest() {
        }

        public void request(String source, String token) {
            System.out.println("请求成功，source=" + source + ",token=" + token);
        }
    }

    private static class RequestIntercept implements MethodInterceptor {
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("拦截请求：" + Arrays.asList(objects));
            Object result = methodProxy.invokeSuper(o, objects);
            System.out.println("记录请求日志");
            return result;
        }
    }


    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(RealRequest.class);
        enhancer.setCallback(new RequestIntercept());
        RealRequest realRequest = (RealRequest) enhancer.create();
        realRequest.request("小程序","1344");
    }
}
